using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.MobileService.Guide;
using B.S.NewMedical.Api.Read.DTOS.Guide;
using B.S.NewMedical.Domain.MobileService;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.MobileService.Guide
{
    /// <summary>
    /// 获取就医指南详情处理器
    /// </summary>
    public class GetGuideDetailHandler : IRequestHandler<GetGuideDetailCommand, ApiResult<GuideDetailDto>>
    {
        private readonly IBaseRepository<GuideArticle> _articleRepository;
        private readonly IBaseRepository<GuideContent> _contentRepository;
        private readonly IBaseRepository<GuideCategory> _categoryRepository;
        private readonly IBaseRepository<ConsultInteract> _interactRepository;
        private readonly ILogger<GetGuideDetailHandler> _logger;
        private readonly IMapper _mapper;

        public GetGuideDetailHandler(
            IBaseRepository<GuideArticle> articleRepository,
            IBaseRepository<GuideContent> contentRepository,
            IBaseRepository<GuideCategory> categoryRepository,
            IBaseRepository<ConsultInteract> interactRepository,
            ILogger<GetGuideDetailHandler> logger,
            IMapper mapper)
        {
            _articleRepository = articleRepository;
            _contentRepository = contentRepository;
            _categoryRepository = categoryRepository;
            _interactRepository = interactRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<GuideDetailDto>> Handle(GetGuideDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取就医指南详情，文章ID：{ArticleId}", request.ArticleId);

                // 获取文章信息
                var article = await _articleRepository.GetAll()
                    .FirstOrDefaultAsync(a => a.Id == request.ArticleId && !a.IsDeleted, cancellationToken);

                if (article == null)
                {
                    return new ApiResult<GuideDetailDto>
                    {
                        Code = ApiEnum.Error,
                        Msg = "文章不存在或已被删除"
                    };
                }

                // 获取文章内容
                var content = await _contentRepository.GetAll()
                    .FirstOrDefaultAsync(c => c.ArticleId == request.ArticleId && !c.IsDeleted, cancellationToken);

                if (content == null)
                {
                    return new ApiResult<GuideDetailDto>
                    {
                        Code = ApiEnum.Error,
                        Msg = "文章内容不存在"
                    };
                }

                // 获取分类信息
                var category = await _categoryRepository.GetAll()
                    .FirstOrDefaultAsync(c => c.Id == article.CatId && !c.IsDeleted, cancellationToken);

                // 构建文章DTO
                var articleDto = new GuideArticleDto
                {
                    Id = article.Id,
                    CatId = article.CatId,
                    CategoryName = category?.Name ?? "未知分类",
                    Title = article.Title,
                    CoverImg = article.CoverImg,
                    ViewCnt = article.ViewCnt,
                    CreatedAt = article.CreatedAt
                };

                // 构建互动状态DTO
                var interactStatus = new GuideInteractStatusDto
                {
                    IsLiked = false,
                    IsFavorited = false
                };

                // 如果提供了用户ID，则获取互动状态
                if (request.UserId.HasValue)
                {
                    var userInteracts = await _interactRepository.GetAll()
                        .Where(i => !i.IsDeleted && i.UserId == request.UserId.Value && 
                               i.ObjType == "guide" && i.ObjId == request.ArticleId)
                        .ToListAsync(cancellationToken);

                    interactStatus.IsLiked = userInteracts.Any(i => i.Action == "like");
                    interactStatus.IsFavorited = userInteracts.Any(i => i.Action == "fav");
                }

                // 构建详情DTO
                var detailDto = new GuideDetailDto
                {
                    Article = articleDto,
                    ContentHtml = content.ContentHtml,
                    UpdatedAt = content.UpdatedAt,
                    InteractStatus = interactStatus
                };

                // 更新浏览量（实际应在写API中处理）
                // article.ViewCnt += 1;
                // await _articleRepository.UpdateAsync(article);

                return new ApiResult<GuideDetailDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取就医指南详情成功",
                    Data = detailDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取就医指南详情时发生异常");
                return new ApiResult<GuideDetailDto>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取就医指南详情失败：" + ex.Message
                };
            }
        }
    }
} 